package com.peng.leetcode.other;

import java.util.Deque;
import java.util.LinkedList;

/**
 * Calculate
 *
 * 227. 基本计算器 II
 *
 * @author: lupeng6
 * @create: 2021/3/11 14:12
 */
public class Calculate {

    public static void main(String[] args) {
        String s = "3+2*2";
        System.out.println(new Calculate().calculate(s));
    }


    public int calculate(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        Deque<Integer> stack = new LinkedList<>();
        char preSign = '+';
        int num = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (Character.isDigit(s.charAt(i))) {
                num = num * 10 + (s.charAt(i) - '0');
            }
            if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == n - 1) {
                if (preSign == '+') {
                    stack.push(num);
                } else if (preSign == '-') {
                    stack.push(-num);
                } else if (preSign == '*') {
                    stack.push(stack.pop() * num);
                } else if (preSign == '/') {
                    stack.push(stack.pop() / num);
                }
                num = 0;
                preSign = s.charAt(i);
            }
        }
        int answer = 0;
        while (!stack.isEmpty()) {
            answer += stack.pop();
        }
        return answer;
    }
}
